﻿using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PC.PickleJar.VisualStudioIntegration.AutoCompletion
{
	internal class SourceItemCompletionSource : ICompletionSource
	{
		private bool isDisposed;
		private SourceItemCompletionProvider sourceProvider;
		private ITextBuffer textBuffer;
		private List<Completion> completions;		

		public SourceItemCompletionSource(SourceItemCompletionProvider sourceProvider, ITextBuffer textBuffer)
		{
			this.sourceProvider = sourceProvider;
			this.textBuffer = textBuffer;
			this.completions = new List<Completion>();
		}

		public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
		{
			List<String> items = new List<string>();
			items.Add("Bender");
			items.Add("Fry");
			items.Add("Frank");
			items.Add("Dweezil");
			items.Add("Moon");

			this.completions.Clear();
			this.completions.AddRange(items.Select(item => new Completion(item, item, item, null, null)));

			completionSets.Add(new CompletionSet(
				"Source Items",
				"Source Items",
				this.FindTokenSpanAtPosition(session.GetTriggerPoint(this.textBuffer), session),
				this.completions,
				null));
		}

		private ITrackingSpan FindTokenSpanAtPosition(ITrackingPoint trackingPoint, ICompletionSession session)
		{
			SnapshotPoint currentPoint = (session.TextView.Caret.Position.BufferPosition) - 1;

			ITextStructureNavigator navigator = this.sourceProvider.NavigatorService.GetTextStructureNavigator(this.textBuffer);
			TextExtent extent = navigator.GetExtentOfWord(currentPoint);

			return currentPoint.Snapshot.CreateTrackingSpan(extent.Span, SpanTrackingMode.EdgeInclusive);
		}

		public void Dispose()
		{
			if (!isDisposed)
			{
				GC.SuppressFinalize(this);
				isDisposed = true;
			}
		}
	}
}
